package com.xcj.juhe.tool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignSortTool {

    /**
     * 按照 key=value 的形式生成字符串
     *
     * @param param
     * @param sort            键是否排序
     * @param isWithQuotation 值是否需要加双引号
     * @return
     */
    public static String createLinkString(Map<String, Object> param, boolean sort, boolean isWithQuotation) {
        List<String> keys = new ArrayList<String>(param.keySet());
        if (sort) {
            Collections.sort(keys);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = "";

            if (null != param.get(key)) {
                value = param.get(key) + "";
            }

            if (isWithQuotation) {
                sb.append(String.format("%s=\"%s\"", key, value));
            } else {
                sb.append(String.format("%s=%s", key, value));
            }
            if (i != keys.size() - 1) {
                sb.append("&");
            }
        }
        return sb.toString();
    }

    public static String createLinkString2(Map<String, String> param, boolean sort, boolean isWithQuotation) {
        List<String> keys = new ArrayList<String>(param.keySet());
        if (sort) {
            Collections.sort(keys);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = "";

            if (null != param.get(key)) {
                value = param.get(key);
            }

            if (isWithQuotation) {
                sb.append(String.format("%s=\"%s\"", key, value));
            } else {
                sb.append(String.format("%s=%s", key, value));
            }
            if (i != keys.size() - 1) {
                sb.append("&");
            }
        }
        return sb.toString();
    }

}
